<?php


namespace app\backend\service;
use app\backend\model\MenuModel;
use app\common\RootService;

class MenuService extends RootService
{
    /**
     * 菜单列表
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function lists()
    {
        // 权限菜单
        $myAuthMenuIds = array_column((new AuthService())->myAuth(), 'id');
        // 获取数据
        $menuList = $this->menuModel()->with('subMenu')->select()->toArray();
        // 数据处理
        empty($menuList) || array_walk($menuList, function ($row) use (&$returnAuths, $myAuthMenuIds) {
            $subMenus = $row['subMenu'];
            $row['subMenu'] = [];
            foreach ($subMenus as &$val) {
                $val['url'] = join('/', [$val['app'], $val['controller'], $val['action']]);
                // 加入子菜单
                in_array($val['id'], $myAuthMenuIds) && array_push($row['subMenu'], $val);
            }
            // 收集满足条件的菜单
            empty(count($row['subMenu'])) || $returnAuths[] = $row;
        });
        // 返回
        return $returnAuths ?? [];
    }

    /**
     * 数据平台快捷方式
     * @return array
     */
    public function menuLink()
    {
        // 数据源
        $menuLink = MenuModel::where(['link' => 1, 'is_show' => 1, 'is_menu' => 1])->column('title, app, controller, action, icon');
        // 数据处理
        empty($menuLink) || array_walk($menuLink, function (&$row) {
            $row['url'] = realImgUrl(join('/', [$row['app'], $row['controller'], $row['action']]));
        });
        return $menuLink;
    }

    /**
     * 左侧菜单模型
     * @return MenuModel
     */
    protected function menuModel()
    {
        // 筛选条件
        $where = ['parent_id' => 0, 'is_show' => 1, 'app' => 'backend'];
        // 筛选字段
        $fields = ['id', 'parent_id', 'title', 'app', 'controller', 'action', 'icon', 'is_menu'];
        // 返回筛选结果
        return MenuModel::where($where)->field($fields)->order(['sort' => 'desc', 'id' => 'asc']);
    }
}